using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls;

namespace Be.Timvw.Framework.Web.UI.Adapters
{
    public class LoginStatusAdapter : ControlAdapter
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LoginStatus loginStatus = this.Control as LoginStatus;
            if(loginStatus == null) return;

            loginStatus.LoggedOut += this.loginStatus_LoggedOut;
        }

        protected virtual void loginStatus_LoggedOut(object sender, EventArgs e)
        {
            LoginStatus loginStatus = this.Control as LoginStatus;
            if(loginStatus == null) return;

            if(loginStatus.LogoutAction != LogoutAction.Refresh)
            {
                return;
            }

            HttpContext httpContext = HttpContext.Current;
            if(httpContext == null) return;


            HttpRequest httpRequest = httpContext.Request;
            if(httpRequest == null) return;

            if(!string.Equals(httpRequest.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) return;

            NameValueCollection queryString = httpRequest.QueryString;
            if(queryString == null) return;
            if(queryString.Count <= 0) return;

            string clickedParameterName = LinkButtonAdapter.ClickedParameterName;
            string clickedParameter = queryString[clickedParameterName];
            if(string.IsNullOrEmpty(clickedParameter)) return;

            HttpResponse httpResponse = httpContext.Response;
            if(httpResponse == null) return;

            NameValueCollection writableQuery = new NameValueCollection();
            foreach(string key in queryString.Keys)
            {
                if(key != clickedParameterName)
                {
                    writableQuery.Add(key, queryString[key]);
                }
            }

            Uri httpRequestUrl = httpRequest.Url;
            if(httpRequestUrl == null) return;

            Uri httpRequestUrlWithoutClickedParameter = UriHelper.ReplaceQueryString(httpRequestUrl, writableQuery);
            httpResponse.Redirect(httpRequestUrlWithoutClickedParameter.ToString(), true);
        }
    }
}